﻿using System;
using Caliburn.Micro;
using Caliburn.Micro.Extensions;

namespace SimplePopup.ViewModels.Dialog
{
    public class DialogHostViewModel : Conductor<object>, IDialogHost
    {
        private IDialogHostAware _dialogHostAware;

        public bool CanOk
        {
            get { return _dialogHostAware == null || _dialogHostAware.IsComplete; }
        }

        #region IDialogHost Members

        public DialogResult DialogResult { get; private set; }

        #endregion

        public event EventHandler<ResultCompletionEventArgs> Completed;

        public DialogHostViewModel Start(string title, object content)
        {
            DisplayName = title;
            DialogResult = DialogResult.Cancel;

            _dialogHostAware = content as IDialogHostAware;
            if (_dialogHostAware != null)
            {
                _dialogHostAware.OnHostLoaded(this);
                _dialogHostAware.CompleteChanged -= CompleteChanged;
                _dialogHostAware.CompleteChanged += CompleteChanged;
            }

            ActivateItem(content);
            return this;
        }

        private void CompleteChanged(object sender, EventArgs e)
        {
            NotifyOfPropertyChange(() => CanOk);
        }

        public void Ok()
        {
            DialogResult = DialogResult.Ok;
            TryClose();
        }

        public void Cancel()
        {
            DialogResult = DialogResult.Cancel;
            TryClose();
        }

        protected override void OnDeactivate(bool close)
        {
            if (close)
            {
                OnComplete();
                if (_dialogHostAware != null)
                {
                    _dialogHostAware.CompleteChanged -= CompleteChanged;
                    _dialogHostAware.OnHostLoaded(null);
                }

                ActiveItem = null;
                _dialogHostAware = null;
            }

            base.OnDeactivate(close);
        }

        protected void OnComplete()
        {
            if (Completed == null) return;

            var args = new ResultCompletionEventArgs { WasCancelled = DialogResult == DialogResult.Cancel };
            EventFns.RaiseOnce(ref Completed, this, args);
        }
    }
}